
// In global scope
var setFlash = function(alert, msg) {
	var alertHtml = '<div class="alert alert-'+alert+' alert-dismissable">\
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'+msg+'</div>';
	$("#alert").html(alertHtml);
}
	
var createTable = function(sheet) {
	sheet = reorderSheetCells(sheet);
	
    var tablecontents = '';
    tablecontents = "<table class='table table-striped table-bordered table-hover table-condensed'>";
    // columns
    tablecontents += '<tr>';
    for (var i=0; i<sheet.columns.length; i++) {
    	var column = sheet.columns[i];
    	tablecontents += '<th class="column col'+i+'" pos='+i+'>'+column.title+'</th>';
    }
    tablecontents += '</tr>';
    // row cell data
    var rowlen = sheet.rows.length > 5 ? 5 : sheet.rows.length;	// up to 5 rows
    for (var i=0; i<rowlen; i++) {
    	var row = sheet.rows[i];
    	tablecontents += '<tr>';
    	for (var j=0; j<row.cells.length; j++) {
    		var cell = row.cells[j];
    		if (cell !== undefined) {
    			tablecontents += '<td class="column col'+j+'" pos='+j+'>' + cell.displayValue + '</td>';
    		} else {	// empty cell
    			tablecontents += '<td class="column col'+j+'" pos='+j+'></td>';
    		}
    	}
    	tablecontents += '</tr>';
   }
   tablecontents += '</table>';
   //document.getElementById("rowtable").innerHTML = tablecontents;
   $('#rowtable').html(tablecontents);
}

// get sheet data, and draw table
var getSheetData = function(sheetId) {
	$.get('sheet/'+sheetId, function(data) {
		window.sheet = data.sheet;
		if (data.sheet !== null) {
			createTable(data.sheet);
		} else {
			setFlash('danger', 'Error on getting sheet data, try again');
		}
	},'json');
}

var reorderSheetCells = function(sheet) {

    // window.gchart2 = sheet;   // debug only
    
    // build columnIndexMap of column.id -> column.index
    var columnIndexMap = {};
    sheet.columns.forEach(function(column, index, array) {
        columnIndexMap[column.id] = column.index;
    });

    // reorder row data with column index order
    var tmpRows = [];
    //sheet.rows.forEach(function(row, i) {
    var rowlen = sheet.rows.length > 5 ? 5 : sheet.rows.length;	// up to 5 rows
    for (var i=0; i<rowlen; i++) {
    	var row = sheet.rows[i];
        tmpRows[i] = row;
        var tmpCells = [];
        // make fixed size
        tmpCells[sheet.columns.length-1] = undefined;
        row.cells.forEach(function(cell, j) {
            var k = columnIndexMap[cell.columnId];
            tmpCells[k] = cell;
        });

        tmpRows[i].cells = tmpCells;

    };
    // set the reordered row data to sheet rows
    sheet.rows = tmpRows;
    window.sheet2 = sheet;     // debug only
    //callback(sheet, columnIndexMap);	//pass the sheet back
    return sheet;
}
